<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no">
    <title>技师顾客管理</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css">
    <style>
        body {
            background-color: #f8f9fa;
            padding-top: 15px;
            padding-bottom: 20px;
        }
        .card {
            margin-bottom: 15px;
            border-radius: 10px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.1);
        }
        .card-header {
            background-color: #6c757d;
            color: white;
            border-radius: 10px 10px 0 0 !important;
        }
        .btn-primary {
            background-color: #007bff;
        }
        .reservation-status {
            font-weight: bold;
        }
        .status-1 {color: #ffc107;} /* 待确认 */
        .status-2 {color: #17a2b8;} /* 已确认 */
        .status-3 {color: #28a745;} /* 已完成 */
        .status-4 {color: #dc3545;} /* 已取消 */
        .no-data {
            text-align: center;
            padding: 20px;
            color: #6c757d;
        }
        .nav-tabs .nav-link.active {
            font-weight: bold;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="row">
            <div class="col-12">
                <h4 class="text-center mb-4">技师顾客管理</h4>
                <div id="loading" class="text-center">
                    <div class="spinner-border text-primary" role="status">
                        <span class="sr-only">加载中...</span>
                    </div>
                    <p>正在验证身份...</p>
                </div>
                
                <div id="unauthorized" class="alert alert-danger text-center" style="display:none;">
                    <strong>无访问权限!</strong> 您不是技师，无法访问此页面。
                </div>
                
                <div id="error" class="alert alert-danger text-center" style="display:none;">
                    <strong>出错了!</strong> <span id="errorMsg">加载数据时出错</span>
                </div>
                
                <div id="mainContent" style="display:none;">
                    <ul class="nav nav-tabs mb-3" id="myTab" role="tablist">
                        <li class="nav-item" role="presentation">
                            <a class="nav-link active" id="reservation-tab" data-toggle="tab" href="#reservation" role="tab">我的预约</a>
                        </li>
                        <li class="nav-item" role="presentation">
                            <a class="nav-link" id="customers-tab" data-toggle="tab" href="#customers" role="tab">我的顾客</a>
                        </li>
                    </ul>
                    
                    <div class="tab-content" id="myTabContent">
                        <!-- 预约管理标签页 -->
                        <div class="tab-pane fade show active" id="reservation" role="tabpanel">
                            <div class="form-group">
                                <select class="form-control" id="statusFilter">
                                    <option value="">全部状态</option>
                                    <option value="1">待确认</option>
                                    <option value="2">已确认</option>
                                    <option value="3">已完成</option>
                                    <option value="4">已取消</option>
                                </select>
                            </div>
                            
                            <div id="reservationsList">
                                <!-- 预约列表将通过JS动态加载 -->
                            </div>
                        </div>
                        
                        <!-- 顾客列表标签页 -->
                        <div class="tab-pane fade" id="customers" role="tabpanel">
                            <div class="form-group">
                                <input type="text" class="form-control" id="customerSearch" placeholder="搜索顾客姓名或电话...">
                            </div>
                            
                            <div id="customersList">
                                <!-- 顾客列表将通过JS动态加载 -->
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
    
    <script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.1/dist/umd/popper.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.min.js"></script>
    <script>
        // 定义全局变量存储微信openid和技师信息
        var wxOpenid = "";
        var staffInfo = null;
        
        $(document).ready(function() {
            // 获取URL参数中的openid
            const urlParams = new URLSearchParams(window.location.search);
            wxOpenid = urlParams.get('openid') || "";
            
            if (!wxOpenid) {
                showError("缺少必要的微信授权信息，请重新进入");
                return;
            }
            
            // 验证技师身份
            verifyStaffIdentity();
            
            // 绑定事件
            $('#statusFilter').change(function() {
                loadReservations();
            });
            
            $('#customerSearch').on('keyup', function() {
                filterCustomers($(this).val());
            });
        });
        
        // 验证技师身份
        function verifyStaffIdentity() {
            $.ajax({
                url: '/wx/verifyStaffIdentity',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({ openid: wxOpenid }),
                success: function(response) {
                    if (response.code === 200) {
                        staffInfo = response.data;
                        $('#loading').hide();
                        $('#mainContent').show();
                        
                        // 加载预约和顾客数据
                        loadReservations();
                        loadCustomers();
                    } else {
                        $('#loading').hide();
                        $('#unauthorized').show();
                    }
                },
                error: function(xhr) {
                    $('#loading').hide();
                    showError("验证身份失败: " + (xhr.responseJSON ? xhr.responseJSON.msg : "未知错误"));
                }
            });
        }
        
        // 加载预约列表
        function loadReservations() {
            if (!staffInfo) return;
            
            const status = $('#statusFilter').val();
            
            $('#reservationsList').html('<div class="text-center p-3"><div class="spinner-border spinner-border-sm text-primary"></div> 加载中...</div>');
            
            $.ajax({
                url: '/wx/getStaffReservations',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({ 
                    openid: wxOpenid,
                    staffPid: staffInfo.pid,
                    status: status
                }),
                success: function(response) {
                    if (response.code === 200) {
                        renderReservations(response.data);
                    } else {
                        $('#reservationsList').html('<div class="alert alert-danger">加载预约失败: ' + response.msg + '</div>');
                    }
                },
                error: function() {
                    $('#reservationsList').html('<div class="alert alert-danger">网络错误，请稍后重试</div>');
                }
            });
        }
        
        // 渲染预约列表
        function renderReservations(reservations) {
            if (!reservations || reservations.length === 0) {
                $('#reservationsList').html('<div class="no-data">暂无预约记录</div>');
                return;
            }
            
            let html = '';
            
            reservations.forEach(function(item) {
                const statusText = getStatusText(item.status);
                const statusClass = `status-${item.status}`;
                
                html += `
                <div class="card">
                    <div class="card-header d-flex justify-content-between align-items-center">
                        <div>${item.customerName} - ${item.customerPhone}</div>
                        <span class="reservation-status ${statusClass}">${statusText}</span>
                    </div>
                    <div class="card-body">
                        <p class="card-text"><strong>服务内容:</strong> ${item.serviceContent}</p>
                        <p class="card-text"><strong>预约时间:</strong> ${formatDateTime(item.appointmentTime)}</p>
                        <p class="card-text"><strong>服务房间:</strong> ${item.roomNo || '未分配'}</p>
                        
                        <div class="text-right mt-2">`;
                
                // 根据状态显示不同按钮
                if (item.status === 1) { // 待确认
                    html += `
                        <button class="btn btn-sm btn-primary mr-2" onclick="updateReservationStatus(${item.id}, 2)">确认预约</button>
                        <button class="btn btn-sm btn-danger" onclick="updateReservationStatus(${item.id}, 4)">取消预约</button>`;
                } else if (item.status === 2) { // 已确认
                    html += `
                        <button class="btn btn-sm btn-success mr-2" onclick="updateReservationStatus(${item.id}, 3)">完成服务</button>
                        <button class="btn btn-sm btn-danger" onclick="updateReservationStatus(${item.id}, 4)">取消预约</button>`;
                }
                
                html += `
                        </div>
                    </div>
                </div>`;
            });
            
            $('#reservationsList').html(html);
        }
        
        // 更新预约状态
        function updateReservationStatus(id, status) {
            if (!confirm('确定要更改此预约状态吗？')) return;
            
            $.ajax({
                url: '/wx/updateReservationStatus',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({ 
                    id: id,
                    status: status,
                    openid: wxOpenid
                }),
                success: function(response) {
                    if (response.code === 200) {
                        alert('更新成功');
                        loadReservations();
                    } else {
                        alert('更新失败: ' + response.msg);
                    }
                },
                error: function() {
                    alert('网络错误，请稍后重试');
                }
            });
        }
        
        // 加载顾客列表
        function loadCustomers() {
            $('#customersList').html('<div class="text-center p-3"><div class="spinner-border spinner-border-sm text-primary"></div> 加载中...</div>');
            
            let requestData = { openid: wxOpenid };
            
            // 如果有staffInfo，添加staffPid参数
            if (staffInfo && staffInfo.pid) {
                requestData.staffPid = staffInfo.pid;
            }
            
            $.ajax({
                url: '/wx/getStaffCustomers',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(requestData),
                success: function(response) {
                    if (response.code === 200) {
                        renderCustomers(response.data);
                    } else {
                        $('#customersList').html('<div class="alert alert-danger">加载顾客失败: ' + response.msg + '</div>');
                    }
                },
                error: function() {
                    $('#customersList').html('<div class="alert alert-danger">网络错误，请稍后重试</div>');
                }
            });
        }
        
        // 渲染顾客列表
        function renderCustomers(customers) {
            if (!customers || customers.length === 0) {
                $('#customersList').html('<div class="no-data">暂无顾客记录</div>');
                return;
            }
            
            let html = '';
            
            customers.forEach(function(item) {
                const vipLevel = getVipLevelText(item.vipLevel);
                const lastVisit = item.lastVisit ? formatDate(item.lastVisit) : '从未到店';
                
                html += `
                <div class="card customer-card" data-name="${item.name}" data-phone="${item.phone}">
                    <div class="card-body">
                        <div class="d-flex justify-content-between align-items-center mb-2">
                            <h5 class="card-title mb-0">${item.name} ${item.gender === 1 ? '(先生)' : '(女士)'}</h5>
                            <span class="badge badge-${item.vipLevel > 0 ? 'warning' : 'secondary'}">${vipLevel}</span>
                        </div>
                        <p class="card-text"><strong>电话:</strong> ${item.phone || '未填写'}</p>
                        <p class="card-text"><strong>年龄:</strong> ${item.age || '未知'}</p>
                        <p class="card-text"><strong>最近到店:</strong> ${lastVisit}</p>
                        <p class="card-text"><strong>累计消费:</strong> ¥${item.totalConsumption || '0.00'}</p>
                    </div>
                </div>`;
            });
            
            $('#customersList').html(html);
        }
        
        // 筛选顾客
        function filterCustomers(keyword) {
            if (!keyword) {
                $('.customer-card').show();
                return;
            }
            
            keyword = keyword.toLowerCase();
            
            $('.customer-card').each(function() {
                const name = $(this).data('name').toLowerCase();
                const phone = $(this).data('phone') ? $(this).data('phone').toString() : '';
                
                if (name.includes(keyword) || phone.includes(keyword)) {
                    $(this).show();
                } else {
                    $(this).hide();
                }
            });
        }
        
        // 显示错误信息
        function showError(message) {
            $('#loading').hide();
            $('#errorMsg').text(message);
            $('#error').show();
        }
        
        // 格式化日期时间
        function formatDateTime(timestamp) {
            if (!timestamp) return '未设置';
            const date = new Date(timestamp);
            return date.getFullYear() + '-' + 
                   padZero(date.getMonth() + 1) + '-' + 
                   padZero(date.getDate()) + ' ' + 
                   padZero(date.getHours()) + ':' + 
                   padZero(date.getMinutes());
        }
        
        // 格式化日期
        function formatDate(timestamp) {
            if (!timestamp) return '未设置';
            const date = new Date(timestamp);
            return date.getFullYear() + '-' + 
                   padZero(date.getMonth() + 1) + '-' + 
                   padZero(date.getDate());
        }
        
        // 数字补零
        function padZero(num) {
            return num < 10 ? '0' + num : num;
        }
        
        // 获取预约状态文字
        function getStatusText(status) {
            switch (status) {
                case 1: return '待确认';
                case 2: return '已确认';
                case 3: return '已完成';
                case 4: return '已取消';
                default: return '未知状态';
            }
        }
        
        // 获取VIP等级文字
        function getVipLevelText(level) {
            switch (level) {
                case 0: return '普通会员';
                case 1: return '白银会员';
                case 2: return '黄金会员';
                case 3: return '白金会员';
                case 4: return '钻石会员';
                default: return '普通会员';
            }
        }
    </script>
</body>
</html> 